package com.bm.jarquickstart.controller;

import com.bm.jarquickstart.entity.Files;
import com.bm.jarquickstart.entity.JarPackage;
import com.bm.jarquickstart.entity.LayuiR;
import com.bm.jarquickstart.util.FileUtil;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @author 港某
 * @datetime 2021/4/25 17:21
 */
@CrossOrigin
@RestController
@RequestMapping(value = "index")
public class IndexController {

    @RequestMapping(value = "getNowTime", method = {RequestMethod.GET})
    @ApiOperation(value = "获取当前时间")
    String getNowTime() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
    }

    @RequestMapping(value = "refreshFileList", method = {RequestMethod.GET})
    @ApiOperation(value = "刷新文件缓存")
    void refreshFileList() {
        FileUtil.getFileList();
    }

    @RequestMapping(value = "getAllFile", method = {RequestMethod.POST})
    @ApiOperation(value = "获取所有文件")
    LayuiR<List<JarPackage>> getAllJar(String name) {
        List<JarPackage> jarPackageList = new LinkedList<>();
        Map<String, File> fileMap = FileUtil.FILE_MAP;
        fileMap.forEach((k, v) -> {
            JarPackage jarPackage = new JarPackage(k, v);
            if (StringUtils.isNotBlank(name)) {
                if (jarPackage.getName().contains(name)) {
                    jarPackageList.add(jarPackage);
                }
            } else {
                jarPackageList.add(jarPackage);
            }

        });
        return LayuiR.page(jarPackageList.size(), jarPackageList);
    }

    @RequestMapping(value = "fileStart", method = {RequestMethod.POST})
    @ApiOperation(value = "启动")
    void fileStart(String[] objIds) {
        if (objIds == null) {
            return;
        }
        for (String objId : objIds) {
            File file = FileUtil.FILE_MAP.get(objId);
            if (file == null) {
                continue;
            }
            System.out.println(file.getAbsolutePath());
        }
    }


}
